package com.qw.soul.permission;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.provider.Settings;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.CheckResult;
import androidx.annotation.Nullable;

import com.qw.soul.permission.bean.Permission;
import com.qw.soul.permission.bean.Special;
import com.qw.soul.permission.debug.PermissionDebug;
import com.qw.soul.permission.support.PermissionsPageManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.M;
import static com.qw.soul.permission.support.PermissionsPageManager.MANUFACTURER_MEIZU;
import static com.qw.soul.permission.support.PermissionsPageManager.MANUFACTURER_OPPO;
import static com.qw.soul.permission.support.PermissionsPageManager.MANUFACTURER_XIAOMI;
/**
 * @author cd5160866
 */
public class PermissionTools
{

    private static final String TAG = PermissionTools.class.getSimpleName();

    private static List<String> forceSet = new ArrayList<>(Arrays.asList(MANUFACTURER_XIAOMI, MANUFACTURER_MEIZU));

    private static List<String> underMSet = new ArrayList<>(Arrays.asList(MANUFACTURER_XIAOMI, MANUFACTURER_MEIZU, MANUFACTURER_OPPO));

    /**
     * 小米和魅族需要特殊处理
     * @return
     */
    public static boolean isForceManufacturer()
    {
        return forceSet.contains(PermissionsPageManager.getManufacturer());
    }

    /**
     * 小米 魅族 oppo低于6.0也有运行权限
     * @return
     */
    public static boolean isRuntimePermissionSupportBelowApiM()
    {
        String m = PermissionsPageManager.getManufacturer();
        if(!TextUtils.isEmpty(m))
        {
            return underMSet.contains(m.toLowerCase()) && PermissionTools.isAndroid5_6();
        }
        return false;
    }

    /**
     * 低于6.0
     * @return
     */
    public static boolean isBelowAndroid6()
    {
        return android.os.Build.VERSION.SDK_INT < M;
    }

    /**
     * 5.0 - 6.0
     * @return
     */
    public static boolean isAndroid5_6()
    {
        int localSdkVersion = android.os.Build.VERSION.SDK_INT;
        return localSdkVersion >= LOLLIPOP  && localSdkVersion < M;
    }

    @CheckResult
    @Nullable
    public static Intent getSpecialPermissionIntent(Context context, Special specialPermission)
    {
        Intent intent;
        switch (specialPermission)
        {
            case SYSTEM_ALERT:
            case DRAW_WINDOW:
                intent = getDrawOverPermissionIntent(context);
                break;
            case UNKNOWN_APP_SOURCES:
                intent = getInstallPermissionIntent(context);
                break;
            case NOTIFICATION:
            default:
                intent = getAppManageIntent(context);
                break;
        }
        return intent;
    }

    private static Intent getDrawOverPermissionIntent(Context context)
    {
        Uri packageURI = Uri.parse("package:" + context.getPackageName());
        //system support
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            return new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, packageURI);
        }
        //  check by appOps, so go to Application settings
        return getAppManageIntent(context);
    }

    private static Intent getInstallPermissionIntent(Context context)
    {
        Uri packageURI = Uri.parse("package:" + context.getPackageName());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            return new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        }
        return null;
    }

    private static Intent getAppManageIntent(Context context)
    {
        Intent intent;
        try
        {
            intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);
        } catch (Exception e)
        {
            intent = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
        }
        return intent;
    }

    static Permission[] convert(List<Permission> permissions)
    {
        return permissions.toArray(new Permission[0]);
    }

    static boolean assertMainThread()
    {
        return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
    }

    static void toast(Context context, String message)
    {
        if (null == context)
        {
            return;
        }
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    static void jumpAppDetail(Activity activity, int requestCode)
    {
        if (!isActivityAvailable(activity))
        {
            PermissionDebug.e(TAG, "activity status error");
        }
        Intent appDetailIntent = getAppManageIntent(activity);
        if (null == appDetailIntent)
        {
            PermissionDebug.e(TAG, "get system intent failed");
        }
        activity.startActivityForResult(appDetailIntent, requestCode);
    }

    /**
     * 判断Activity 是否可用
     *
     * @param activity 目标Activity
     * @return true of false
     */
    public static boolean isActivityAvailable(Activity activity)
    {
        if (null == activity)
        {
            return false;
        }
        if (activity.isFinishing())
        {
            return false;
        }
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 || !activity.isDestroyed();
    }
}
